<template>
  <div class="system-permission">
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="权限名称">
          <el-input v-model="searchForm.name" placeholder="请输入权限名称" clearable />
        </el-form-item>
        <el-form-item label="权限类型">
          <el-select v-model="searchForm.type" placeholder="请选择" clearable>
            <el-option label="菜单" value="menu" />
            <el-option label="按钮" value="button" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="toolbar">
      <el-button type="primary" @click="handleCreate">新建权限</el-button>
      <el-button type="success" @click="handleExpandAll">展开全部</el-button>
    </div>

    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        border
      >
        <el-table-column prop="name" label="权限名称" min-width="200" />
        <el-table-column prop="code" label="权限编码" width="200" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.type === 'menu' ? 'success' : 'primary'">
              {{ row.type === 'menu' ? '菜单' : '按钮' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路由路径" width="200" />
        <el-table-column prop="icon" label="图标" width="100">
          <template #default="{ row }">
            <el-icon v-if="row.icon"><component :is="row.icon" /></el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-switch v-model="row.status" :active-value="1" :inactive-value="0" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleAddChild(row)">添加子权限</el-button>
            <el-button type="text" size="small" style="color: #f56c6c;" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 权限表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '新建权限' : '编辑权限'"
      width="600px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="上级权限" v-if="parentPermission">
          <span>{{ parentPermission.name }}</span>
        </el-form-item>
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入权限编码" />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio label="menu">菜单</el-radio>
            <el-radio label="button">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="路由路径" v-if="formData.type === 'menu'">
          <el-input v-model="formData.path" placeholder="请输入路由路径" />
        </el-form-item>
        <el-form-item label="图标" v-if="formData.type === 'menu'">
          <el-input v-model="formData.icon" placeholder="请输入图标名称" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="formData.sort" :min="0" :max="9999" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="formData.description" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPermissionList, createPermission, updatePermission, deletePermission } from '@/api/wash_service'

export default {
  name: 'SystemPermission',
  setup() {
    const loading = ref(false)
    const submitLoading = ref(false)
    const dialogVisible = ref(false)
    const dialogType = ref('create')
    const formRef = ref()
    const parentPermission = ref(null)

    const searchForm = reactive({
      name: '',
      type: ''
    })

    const tableData = ref([])

    const formData = reactive({
      id: '',
      parentId: '',
      name: '',
      code: '',
      type: 'menu',
      path: '',
      icon: '',
      sort: 0,
      status: 1,
      description: ''
    })

    const formRules = {
      name: [
        { required: true, message: '请输入权限名称', trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入权限编码', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择权限类型', trigger: 'change' }
      ]
    }

    // 加载权限树
    const loadTableData = async () => {
      loading.value = true
      try {
        const res = await getPermissionList(searchForm)
        
        if (res && (res.code === 200 || res.data || res.content)) {
          const data = res.data || res
          tableData.value = data.content || data.records || data || []
        } else {
          tableData.value = []
        }
      } catch (error) {
        console.error('获取权限列表失败:', error)
        ElMessage.warning('获取权限列表失败，请检查网络连接')
        tableData.value = []
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      loadTableData()
    }

    const handleReset = () => {
      Object.assign(searchForm, { name: '', type: '' })
      handleSearch()
    }

    const handleCreate = () => {
      dialogType.value = 'create'
      parentPermission.value = null
      resetFormData()
      dialogVisible.value = true
    }

    const handleEdit = (row) => {
      dialogType.value = 'edit'
      Object.assign(formData, row)
      dialogVisible.value = true
    }

    const handleAddChild = (row) => {
      dialogType.value = 'create'
      parentPermission.value = row
      resetFormData()
      formData.parentId = row.id
      dialogVisible.value = true
    }

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定删除该权限吗？', '提示', { type: 'warning' })
        
        const res = await deletePermission(row.id)
        if (res && (res.code === 200 || res.success)) {
          ElMessage.success('删除成功')
          loadTableData()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除权限失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    const handleExpandAll = () => {
      // 展开/收起所有树节点的逻辑
      ElMessage.info('展开/收起功能')
    }

    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        submitLoading.value = true
        
        let res
        if (dialogType.value === 'create') {
          res = await createPermission(formData)
        } else {
          res = await updatePermission(formData.id, formData)
        }
        
        if (res && (res.code === 200 || res.success)) {
          ElMessage.success(dialogType.value === 'create' ? '创建成功' : '更新成功')
          dialogVisible.value = false
          loadTableData()
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }

    const resetFormData = () => {
      Object.assign(formData, {
        id: '',
        parentId: '',
        name: '',
        code: '',
        type: 'menu',
        path: '',
        icon: '',
        sort: 0,
        status: 1,
        description: ''
      })
    }

    onMounted(() => {
      loadTableData()
    })

    return {
      loading,
      submitLoading,
      dialogVisible,
      dialogType,
      formRef,
      parentPermission,
      searchForm,
      tableData,
      formData,
      formRules,
      handleSearch,
      handleReset,
      handleCreate,
      handleEdit,
      handleAddChild,
      handleDelete,
      handleExpandAll,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.system-permission {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}
</style> 